import logging

from forest.command import Command
from forest.tool import Tool

import time

DEBUG = False

BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)

COLORS = {
    'WARNING'  : YELLOW,
    'INFO'     : WHITE,
    'DEBUG'    : BLUE,
    'CRITICAL' : YELLOW,
    'ERROR'    : RED,
    'RED'      : RED,
    'GREEN'    : GREEN,
    'YELLOW'   : YELLOW,
    'BLUE'     : BLUE,
    'MAGENTA'  : MAGENTA,
    'CYAN'     : CYAN,
    'WHITE'    : WHITE,
}

RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"
BOLD_SEQ  = "\033[1m"

# progress handling

last_progress_name = None
progress = None

import progressbar

logger = logging.getLogger('forest')

def new_progress(progressdata):
    countprogtext = ""
    if progressdata.get('current'):
        countprogtext = "%s of %s" % (progressdata.get('current'), progressdata.get('total'))
      
    text = '%s - %s' % (countprogtext, progressdata.get('name')) 
    widgets = [text, progressbar.Percentage(), ' ', progressbar.Bar()]
    progress = progressbar.ProgressBar(widgets=widgets, maxval=100, term_width=80)
    return progress

def clear_progress_bars():
    global progress, last_progress_name
    progress = None
    last_progress_name = None
    if progress is not None and not progress.finished:
        progress.finish()

def update_progress(val):
    global progress
    if progress is not None and not progress.finished:
        progress.update(val)

def finish():
    pass

def start():
    pass

def cli_handle_command_start(command):
    string = []
    string.append(COLOR_SEQ % (30+GREEN))
    string.append(command.__register__)
    string.append(RESET_SEQ)
    string.append(': started.')
    print ''.join(string)
    #print '### %s %s%s%s ###' % (, BOLD_SEQ, , RESET_SEQ)

def cli_handle_command_finish(command):
    return
    string = []
    string.append(COLOR_SEQ % (30+GREEN))
    string.append(command.__register__)
    string.append(RESET_SEQ)
    string.append(': finished.')
    print ''.join(string)


def cli_handle_command_progress(command, percent=None, level=None, message=''):
    # ugh
    level = level
    if not level:
        level = logging.INFO

    color = BOLD_SEQ


    if level == logging.DEBUG:
        color = COLOR_SEQ % (30+BLUE)

        if not DEBUG:
            return

    if level == logging.WARN:
        color = COLOR_SEQ % (30+YELLOW)

    if level == logging.ERROR:
        color = COLOR_SEQ % (30+RED)

    if message:
        string = []
        string.append('- ')
        string.append(command.__register__)
        string.append(': ')
        string.append(color)
        string.append(' ')
        string.append(message)
        string.append(RESET_SEQ)
        print ''.join(string)
        logger.debug(message)


Command.SIGNAL_COMMAND_START.connect(cli_handle_command_start)
Command.SIGNAL_COMMAND_PROGRESS.connect(cli_handle_command_progress)
Command.SIGNAL_COMMAND_FINISH.connect(cli_handle_command_finish)


def cli_handle_tool_start(tool, level=logging.DEBUG, message=''):
    clear_progress_bars()

    color = COLOR_SEQ % (30+BLUE)

    # dont print out tool starts if we are not in debug mode
    if not DEBUG and level == logging.DEBUG:
        return

    if level != logging.DEBUG:
        color = BOLD_SEQ

    string = []
    string.append('- ')
    string.append(tool.__register__)
    string.append(': ')
    string.append(color)
    string.append(' ')
    string.append(message)
    string.append(RESET_SEQ)
    print ''.join(string)

def cli_handle_tool_finish(tool, level=None, message=''):
    clear_progress_bars()
    pass

def cli_handle_tool_progress(tool, progressdata=None, level=None, message=''):
    global last_progress_name, progress

    # No progress data, clear up any progress bars
    if not progressdata:
        clear_progress_bars()

    if not level:
        level = logging.INFO

    if level == logging.DEBUG and not DEBUG:
        return

    if message and not progressdata:
        print message
        return

    newprogressneeded = False

    if progressdata and progressdata.get('name') != last_progress_name:
        newprogressneeded = True

    elif progressdata and progress is None:
        newprogressneeded = True

    if newprogressneeded:
        clear_progress_bars()

        progress = new_progress(progressdata)

        last_progress_name = progressdata.get('name')

    if progressdata:
        update_progress(progressdata.get('percent'))


Tool.SIGNAL_TOOL_START.connect(cli_handle_tool_start)
Tool.SIGNAL_TOOL_PROGRESS.connect(cli_handle_tool_progress)
Tool.SIGNAL_TOOL_FINISH.connect(cli_handle_tool_finish)
